import request from "@/axios"
import { ResponseData } from "../../../../constants"
import { UpdateMenu } from "./type"
import { builderMenuTree } from "@/utils"

enum Api {
  queryAllMenus = "/menus/all",
  queryMenu = "/menus/list",
  updateRoleRoutes = "/menus/update",
  saveRoleRoutes = "/menus/save",
  removeRoleRoutes = "/menus/remove",
  menuPermission = "/menus/menu-permission"
}

export const menuApi = {

  queryAllMenusApi: () => {
    return request.get<ResponseData>(Api.queryAllMenus)
  },

  getRoutesMenuTreeApi: async (title = "") => {
    const ret = await request.get<ResponseData>(Api.queryMenu, { title, isAllMenus: true })
    if (ret.code === 200) {
      const allMenus = ret.data.allMenus
      const menuList = ret.data.menuList
      return builderMenuTree(menuList, allMenus)
    } else {
      console.error("获取菜单失败");
      throw new Error("获取菜单失败")
    }
  },

  updateRoleRoutesApi: (menu: any) => {
    return request.post<ResponseData>(Api.updateRoleRoutes, menu)
  },

  saveRoleRoutesApi: (menu: UpdateMenu) => {
    return request.post<ResponseData>(Api.saveRoleRoutes, menu)
  },

  getMenuPermission: (id: string) => {
    return request.get<ResponseData>(Api.menuPermission, { id })
  },

  removeRoleRoutesApi: (id: string) => {
    return request.get<ResponseData>(Api.removeRoleRoutes, { id })
  }

}

